package com.situ.student.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.situ.student.entity.User;
import com.situ.student.service.IUserService;
import com.situ.student.service.impl.UserServiceImpl;

public class UserController extends HttpServlet {
	private IUserService userService = new UserServiceImpl();

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		 // 解决浏览器乱码问题
		 req.setCharacterEncoding("utf-8");
		 String method = req.getParameter("method");
		 switch (method) {
		 case "login":
		 login(req, resp);
		 break;
		 case "logout":
		 logout(req, resp);
		 default:
		 break;
		 }
		 }
		
		 private void logout(HttpServletRequest req, HttpServletResponse resp)
		 throws IOException {
		 HttpSession session=req.getSession();
		 User user=(User) session.getAttribute("user");
		 if(null!=user) {
		 //销毁session
		 session.invalidate();
		 //重定向到登录界面
		 resp.sendRedirect(req.getContextPath()+"/login.jsp");
		 }
		 }
		
		 private void login(HttpServletRequest req, HttpServletResponse resp)
		 throws IOException {
		 // 获取浏览器传过来的 账号 密码
		 String name = req.getParameter("name");
		 String password = req.getParameter("password");
		 // service判断
		 boolean count = userService.login(name, password);
		
		 // 重定向到界面(成功或者失败)
		 if (count) {
		 resp.sendRedirect(req.getContextPath() + "/student?method=list");
		 } else {
		 // 登录失败 重定向到登录失败展示界面
		 resp.sendRedirect(req.getContextPath() + "/shibai.jsp");
		 }
		 }
	}

